using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ApiText.Api.Models;
using ApiText.Api.Params;
using Microsoft.IdentityModel.Tokens;

namespace ApiText.Api.Utils
{
    public class ToKenHelper
    {
        public static string GenerateToKen(ToKenParameter toKenParameter, string user)
        {
            var claims = new[]
            {
               new  Claim(ClaimTypes.Name,user),
               new  Claim(ClaimTypes.Role,"admin"),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(toKenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(toKenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(toKenParameter.AccessExpiration), signingCredentials: credentials);

            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return token;

        }

        public static string ValidateToken(ToKenParameter toKenParameter, RefreshTokenDTO refresh)
        {

            var hanler = new JwtSecurityTokenHandler();

            try
            {
                ClaimsPrincipal claims = hanler.ValidateToken(refresh.Token,
                new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(toKenParameter.Secret)),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                }, out SecurityToken securityToken);

                return claims.Identity.Name;
            }
            catch
            {
                throw new System.ArgumentNullException();
                
            }
        }
    }
}